import ubinascii
import http
from utils import common
import requests
import json

def audio_chat(audio_buffer):
    print("start ai chat")
    audio_base64 = ubinascii.b2a_base64(audio_buffer)
    print(len(audio_base64))
    response = http.POST(
        "https://www.hanxiaoxin.cn:8443/ai/iotasr", {
            "Data": audio_base64,
        }, "json"
    )
    json_data = response.json()
    return http.get_message_data(json_data)

def audio_chat_buffer(audio_buffer):
    print("start ai chat")
    common.collect_gc()
    response = requests.request(
        method = 'POST',
        url = "https://www.hanxiaoxin.cn:8443/ai/iotBuffer",
        headers = { "Content-Type": "audio/wav"},
        data = audio_buffer
    )
    json_data = response.json()
    return http.get_message_data(json_data)

def text_chat(text):
    print("start ai chat")
    common.collect_gc()
    response = requests.request(
        method = 'POST',
        url = "https://www.hanxiaoxin.cn:8443/ai/chat",
        headers = { "Content-Type": "application/json"},
        json = { "content": text }
    )
    json_data = response.json()
    return http.get_message_data(json_data)


if __name__ == '__main__':
    with open('/mic.wav', 'rb') as f:
        buf = f.read()
        audio_chat_buffer(buf)
